import '../public/index'
import url from '../data/url'
import request from '../data/request'
import {tableConfig, header} from '../data/config'
import {getUrlParam, fetch2} from '../data/util'
import store from 'store'

const base = url.base,
  posUpdateUrl = 'admin/equipmentInfo/uploaderV3.json',
  ytjUpdateUrl = 'admin/equipmentInfo/uploaderV2.json',
  posTemplate = '/equipment/v2/downloadIntelligence.json',
  ytjTemplate = '/equipment/v2/downloadIntegrated.json'

let table,
  storeData

const app = {
  apiUrl: null,
  pageType: getUrlParam('type'),
  init() {
    this.getUrl()
    this.initTable()
    this.bindEvent()
    this.leadIn()
  },
  getUrl() {
    // 进入页面初始化接口地址
    switch (this.pageType) {
      case"ytj":
        this.apiUrl = '/admin/equipmentInfo/facade.json'
        break
      case"pos":
        this.apiUrl = '/admin/equipmentInfo/facadeIntelligencepos.json'
        break
    }
  },
  initTable() {
    let columns
    const ytjColumns = [
      {
        field: 'identifierCode',
        title: '设备号',
        valign: 'middle'
      }, {
        field: 'identifier',  // 接口没传终端号
        title: '终端号',
        valign: 'middle'
      },
      {
        field: 'status',
        title: '状态',
        valign: 'middle',
        formatter: function (index, row) {
          let staStr
          switch (row.status) {
            case 1:
              staStr = '刚入库'
              break
            case 2:
              staStr = '使用中'
              break
            case 3:
              staStr = '绑定中'
              break
            case 4:
              staStr = '闲置中'
              break
            case 6:
              staStr = '审核中（停用）'
              break
            case 7:
              staStr = '审核中（解绑）'
              break
            case 5:
            case 8:
              staStr = '审核中（启用）'
              break
          }
          return staStr
        }
      }, {
        propertyArea: 'dName',
        title: '区域',
        valign: 'middle',
        formatter: function (index, row) {
          let addressStr
          switch (row.propertyArea) {
            case  'hd':
              addressStr = '华东'
              break
            case  'hx':
              addressStr = '华西'
              break
            case  'hb':
              addressStr = '华北'
              break
            case  'hn':
              addressStr = '华南'
              break
            case  'hz':
              addressStr = '华中'
              break
          }
          return addressStr
        }
      }, {
        field: 'propertyAddress',
        title: '位置',
        valign: 'middle'
      }, {
        field: 'backup1',
        title: '服务楼盘',
        valign: 'middle'
      }, {
        field: 'serviceType',
        title: '服务类型',
        valign: 'middle',
        formatter: function (index, row) {
          let serviceType
          switch (row.serviceType) {
            case 'ckzm':
              serviceType = '存款证明'
              break
            case 'xf':
              serviceType = '选房'
              break
            case 'fk':
              serviceType = '付款'
              break
          }
          return serviceType
        }
      }, {
        field: 'channel',
        title: '渠道',
        valign: 'middle',
        width: '80px'
      }, {
        field: 'mchName',
        title: '商户名称',
        valign: 'middle',
        width: '80px'
      }, {
        field: 'keyBoardOrPosinfo',
        title: '键盘号',
        valign: 'middle',
        width: '80px'
      }, {
        field: 'versionNumber',
        title: '版本号',
        valign: 'middle',
        width: '80px'
      }
      , {
        field: 'rawUpdateTime',
        title: '时间',
        valign: 'middle',
        width: '80px',
        formatter: function (index, row) {
          if (row.rawUpdateTime) {
            const time = new Date(row.rawUpdateTime)
            return time.toLocaleDateString() + time.toLocaleTimeString()
          } else if (row.rawAddTime) {
            const time = new Date(row.rawAddTime)
            return time.toLocaleDateString() + time.toLocaleTimeString()
          }
        }
      },
      {
        field: 'control',
        valign: 'middle',
        align: 'center',
        width: '170px',
        title: '操作',
        formatter: function (index, row) {
          let btnSecond
          let staStr = {title: null, btnType: 1}
          switch (row.status) {
            case 1:
              staStr.title = '启用'
              break
            case 2:
              staStr.title = '停用'
              break
            case 3:
              staStr.title = '解绑'
              break
            case 4:
              staStr.title = '启用'
              break
            case 5:
              staStr.btnType = 2
              break
            case 6:
              staStr.btnType = 2
              break
            case 7:
              staStr.btnType = 2
              break
            case 8:
              staStr.btnType = 2
              break
          }
          if (staStr.title) {
            btnSecond = `<button type="button" data-identifier="${ staStr.identifier }" data-id="${ row.id }" class="btn btn-default go-info">${staStr.title}</button>`
          }
          const BtnStr = `<div class="btn-group">
                    ${btnSecond ? btnSecond : ''}
                    <button type="button" data-identifier="${ staStr.identifier }" data-id="${ row.id }" class="btn btn-default btn-modify go-info">详情</button>
                  </div>`
          return BtnStr

        }
      }
    ]
    const posColumns = [
      {
        field: 'identifierCode',
        title: '设备号',
        valign: 'middle'
      },
      {
        field: 'status',
        title: '状态',
        valign: 'middle',
        formatter: function (index, row) {
          let staStr
          switch (row.status) {
            case 1:
              staStr = '刚入库'
              break
            case 2:
              staStr = '使用中'
              break
            case 3:
              staStr = '绑定中'
              break
            case 4:
              staStr = '闲置中'
              break
            case 5:
              staStr = '入库启用审批中'
              break
            case 6:
              staStr = '停用审批中'
              break
            case 7:
              staStr = '解绑审批中'
              break
            case 8:
              staStr = '闲置启用审批中'
              break
          }
          return staStr
        }
      }, {
        field: 'propertyArea',
        title: '区域',
        valign: 'middle',
        formatter: function (index, row) {
          let addressStr
          switch (row.propertyArea) {
            case  'hd':
              addressStr = '华东'
              break
            case  'hx':
              addressStr = '华西'
              break
            case  'hb':
              addressStr = '华北'
              break
            case  'hn':
              addressStr = '华南'
              break
            case  'hz':
              addressStr = '华中'
              break
            default:
              addressStr = '无 '
          }
          return addressStr
        }
      }, {
        field: 'propertyAddress',
        title: '位置',
        valign: 'middle'
      },
      {
        field: 'type',
        title: '支付机构',
        valign: 'middle',
        formatter: function (index, row) {
          let type
          switch (row.type) {
            case '2':
              type = '拉卡拉POS'
              break
            case '3':
              type = '银商POS'
              break
          }
          return type
        }
      },
       {
        field: 'backup1',
        title: '服务楼盘',
        valign: 'middle'
      }, {
        field: 'serviceType',
        title: '服务类型',
        valign: 'middle',
        formatter: function (index, row) {
          let serviceType
          switch (row.serviceType) {
            case 'ckzm':
              serviceType = '存款证明'
              break
            case 'xf':
              serviceType = '扫码收定金'
              break
            case 'fk':
              serviceType = '存转定'
              break
          }
          return serviceType
        }
      }, {
        field: 'channel',
        title: '渠道',
        valign: 'middle',
        width: '80px'
      }, {
        field: 'mchName',
        title: '商户名称',
        valign: 'middle',
        width: '80px'
      }, {
        field: 'keyBoardOrPosinfo',
        title: '激活码',
        valign: 'middle',
        width: '80px'
      }
      , {
        field: 'rawUpdateTime',
        title: '时间',
        valign: 'middle',
        width: '80px',
        formatter: function (index, row) {
          if (row.rawUpdateTime) {
            const time = new Date(row.rawUpdateTime)
            return time.toLocaleDateString() + time.toLocaleTimeString()
          } else if (row.rawAddTime) {
            const time = new Date(row.rawAddTime)
            return time.toLocaleDateString() + time.toLocaleTimeString()
          }
        }
      },
      {
        field: 'control',
        valign: 'middle',
        align: 'center',
        width: '170px',
        title: '操作',
        formatter: function (index, row) {
          let btnSecond
          let staStr = {title: null, btnType: 1}
          switch (row.status) {
            case 1:
              staStr.title = '启用'
              break
            case 2:
              staStr.title = '停用'
              break
            case 3:
              staStr.title = '解绑'
              break
            case 4:
              staStr.title = '启用'
              break
            case 5:
              staStr.btnType = 2
              break
            case 6:
              staStr.btnType = 2
              break
            case 7:
              staStr.btnType = 2
              break
            case 8:
              staStr.btnType = 2
              break
          }
          if (staStr.title) {
            btnSecond = `<button type="button" data-identifier="${ staStr.identifier }" data-id="${ row.id }" class="btn btn-default go-info">${staStr.title}</button>`
          }
          const BtnStr = `<div class="btn-group">
                    ${btnSecond ? btnSecond : ''}
                    <button type="button" data-identifier="${ staStr.identifier }" data-id="${ row.id }" class="btn btn-default btn-modify go-info">详情</button>
                  </div>`
          return BtnStr

        }
      },
      
    ]
    if (this.pageType === 'ytj') {
      columns = ytjColumns
    }
    if (this.pageType === 'pos') {
      columns = posColumns
    }

    table = $('#table').bootstrapTable($.extend({}, tableConfig, {
      url: base + this.apiUrl,
      queryParams: function (params) {
        return $.extend({
          currentPage: params.pageNumber,
          pageSize: params.pageSize,
        }, $('#searchForm').serializeObject())
      },
      columns: columns
    }));
  },
  // 绑定事件
  bindEvent() {
    // 点击列表的时候传递数据到全局变量
    table.on('click-row.bs.table', (e, data, el) => {
      storeData = data
      store.set('storeData', data)
    });

// 搜索
    $(document).on('click', '#search-btn', (e) => {
      e.preventDefault();

      table.bootstrapTable('refresh', {
        query: $.extend({
          currentPage: 1,
        }, $('#searchForm').serializeObject())
      })
    });

    // 添加按钮
    $('#add-device').on('click', e => {
      e.preventDefault()
      if (this.pageType === 'ytj') {
        location.href = `./addytj.html`
      }
      if (this.pageType === 'pos') {
        location.href = `./addpos.html`
      }
    })
    // 点击详情页
    $(document).on('click', '#table .go-info', (e) => {
      const id = $(e.target).attr('data-id')
      store.set('storeData', storeData);
      window.location = `./detail.html?type=${this.pageType}&id=${id}`

    });

    // 点击导出按钮
    $(document).on('click', '#download-info', (e) => {
      e.preventDefault()
      const posUrl = '/admin/equipmentInfo/download_excelPos.json'
      const ytjUrl = '/admin/equipmentInfo/download_excelOne.json'
      let apiUrl
      const type = this.pageType
      if (type === 'ytj') {
        apiUrl = ytjUrl
      }
      if (type === 'pos') {
        apiUrl = posUrl
      }
      const data = $('#searchForm').serializeObject()
      data.status = data.statu

      var index = layer.open({type: 3})
      fetch2(apiUrl, data).then(res => {
        if (res.path) {
          location.href = base + res.path
          layer.close(index)
        } else {
          layer.close(index)
          layer.msg(`导出失败`, {
            icon: 5
          })
          setTimeout(() => {
            location.reload()
          }, 1000)
        }
      })
    })
  },
  // 绑定批量导入房源
  leadIn() {
    // 根据页面类型调整批量导入模版链接地址
    let url, updateUrl
    if (this.pageType === 'ytj') {
      url = ytjTemplate
      $('#batch-import-modal #download-template')[0].href = base + url

      updateUrl = ytjUpdateUrl
    }
    if (this.pageType === 'pos') {
      url = posTemplate
      $('#batch-import-modal #download-template')[0].href = base + url

      updateUrl = posUpdateUrl
    }

    const isIe = navigator.appVersion.indexOf("MSIE") !== -1

    const allowType = ['xls', 'xlsx']

    let $el = $('#batch-import-modal-file'),
      $err = $('#batch-import-modal-error'),
      $submit = $('#batch-import-modal-submit');

    $el.on('change', changeHandler)

    function changeHandler($e) {
      const v = $e.target.value
      const f = $e.target.files[0]
      const size = (f.size / 1024).toFixed(1)
      const type = v.substr(v.lastIndexOf('.') + 1)

      console.log(f)
      if (allowType.indexOf(type) === -1) {

        $err.text('文件格式不支持,格式只能是:' + allowType.join(',')).show()
        $submit.attr('disabled', true)

        $el[0].value = ''

        return false
      }

      $err.text('').hide()
      $submit.attr('disabled', false)

      console.log('size:' + size)
      console.log('ext:' + type)
    }

    $submit.unbind('click');

    $submit.on('click', (e) => {
      e.preventDefault;

      let formData = new FormData($('#uploadForm')[0]),
        developerId = $('#developerId').val(),
        developerName = $('#developerId option:selected').text();

      let loading_modal = layer.msg('正在导入...', {
        icon: 16,
        time: 0,
        shade: .5
      })

      formData.append('developerId', developerId + ',' + developerName)

      $submit.attr('disabled', true);

      $.ajax({
        headers: header,
        type: 'POST',
        cache: false,
        url: base + updateUrl,
        processData: false,
        contentType: false,
        dataType: "json",
        data: formData
      })
        .done(function (res) {
          console.log('update response===>>>', res)
          if (res.code === 0) {
            layer.msg(`导入成功`, {
              icon: 6
            })
            setTimeout(() => {
              window.location.reload()
            }, 1000)
          } else {
            layer.msg(res.message, {
              icon: 10
            })
            setTimeout(() => {
              window.location.reload()
            }, 1000)
          }

        })
        .fail(function (err) {
          layer.msg(`导入失败`, {
            icon: 5
          })
          console.log(err)
        })
        .complete(function () {

          // $submit.attr('disabled', false);
          // layer.close(loading_modal);
          // $('#batch-import-modal').modal('hide');
          // window.location.reload()
        })
    })

  }
}
app.init()

const vueApp = new Vue({
  el: '#vue-app',
  data: {
    pageType: null,
    iptPlaceholder: null
  },
  created() {
    const pageType = getUrlParam('type')
    this.pageType = pageType
    this.getPageType()
  },
  methods: {
    // 判断页面类型是一体机还是pos机
    getPageType() {
      const pageType = this.pageType
      const strArr = ['设备号、终端号、位置、服务楼盘、渠道、键盘号、版本号', '设备号、位置、服务楼盘、渠道、激活码']
      if (pageType === 'pos') {
        this.iptPlaceholder = strArr[1]
        return
      }
      if (pageType === 'ytj') {
        this.iptPlaceholder = strArr[0]
        return
      }
    },
    // 获取列表数据
  }
})

